$(function(){
	//监控文本域的字数
	var oDiv=$('.gma-value');
	baseInfoForm.counterCtrl({
		targetSelector:oDiv,
		counterSelector:$('.gma-counter'),
		length:100,
		noticeMsg:'推荐理由已达到上限'
	});
	// 房屋类型焦点的切换；
	$("#gma_room").on("input",function(e){
		var $this=$(this);
		if($this.val()){
			$("#gma_office").focus();
		}
		e.preventDefault();
		return false;
	});
	$("#gma_office").on("input",function(e){
		var $this=$(this);
		if($this.val()){
			$("#gma_toilet").focus();
		}
		e.preventDefault();
		return false;
	});
	//下拉列表遍历;
	var zoomList={
    orientation:["南","南北","东南","西南","其他"],
    houseTypeOne:["0","1","2","3","4","5","6","7","8","9"],
    houseTypeTwo:["0","1","2","3","4","5","6","7","8","9"],
		houseTypeThree:["0","1","2","3","4","5","6","7","8","9"],
		decorate:["毛坯","简装修","中等装修","精装修"],
		houseType:["商品房","公房","商住两用","其他"],
		livingSituation:["自住","租赁","空置"]
	};
  // var $footer=$("#footer");
  // var allInputs=$("input");
  // var allTextArea=$("textarea");
  // allInputs.on("focus",function(e){
  //   $footer.removeClass("fixed");
  // });
  // allInputs.on("blur",function(e){
  //   $footer.addClass("fixed");
  // });
  // allTextArea.on("focus",function(e){
  //   $footer.removeClass("fixed");
  // });
  // allTextArea.on("blur",function(e){
  //   $footer.addClass("fixed");
  // });
	var $orientation=$('#orientation');
	var $decorate=$('#decorate');
	var $houseType=$('#houseType');
	var $livingSituation=$('#livingSituation');
  var $houseTypeOne=$("#gma_room");
  var $houseTypeTwo=$("#gma_office");
  var $houseTypeThree=$("#gma_toilet");
		baseInfoForm.buildSelectByDataList({selector:$orientation,dataList:zoomList.orientation,initTitle:"请选择"});
		baseInfoForm.buildSelectByDataList({selector:$decorate,dataList:zoomList.decorate,initTitle:"请选择"});
		baseInfoForm.buildSelectByDataList({selector:$houseType,dataList:zoomList.houseType,initTitle:"请选择"});
    baseInfoForm.buildSelectByDataList({selector:$livingSituation,dataList:zoomList.livingSituation,initTitle:"请选择"});
    baseInfoForm.buildSelectByDataList({selector:$houseTypeOne,dataList:zoomList.houseTypeOne,initTitle:""});
    baseInfoForm.buildSelectByDataList({selector:$houseTypeTwo,dataList:zoomList.houseTypeTwo,initTitle:""});
		baseInfoForm.buildSelectByDataList({selector:$houseTypeThree,dataList:zoomList.houseTypeThree,initTitle:""});
});
//监控是否有缓存，能否获取id和token
var data=common.getLocalData('H5-agentInfo');
var token=common.getToken();
var $id=$('#agentId');
var $token=$('#token');
var $dialog=$('#gma-alert');
var $mask=$('#gma-mask');
	$id.val(data.id);
	$token.val(token);
var globalHost=common.globalHost;
var submitHousePort=common.submitHousePort;
var url=globalHost+submitHousePort;
var arr=[];
var selectorBtn=$("#upload");
//异步删除图片中的value值
$("#gma_box").off("touchend").on("touchend",".gma_close",function(e){
	var $this=$(this);
	selectorBtn.parent().hasClass('gma_uploadHide')?selectorBtn.parent().removeClass('gma_uploadHide'):null;
    var imgSrc=$this.parent().attr("data-time");
    for(var i=0; i<arr.length; i++) {
        if(arr[i]['time'] == imgSrc) {
          arr.splice(i, 1);
          break;
        }
    }
    $this.parent().remove();
    e.preventDefault();
    return false;
});
baseInfoForm.submit.off('tap').on('tap',function(e){
  //添加埋点
  var buryingKey=19408; 
  var buryingMsg='goldAgentH5'+window.location.pathname+' submit';
  var buryingUrl = "http://qd.innjia.com:8032/ch?key=" + buryingKey + "&url="+ (buryingMsg || "");
      $.get(buryingUrl);
 	var $this=$(this);
  //将图片的隐藏域做处理
  var list=arr.map(function(ele,idx){
    return ele.record;
  }).join(",");
  // console.log(list);
  $("#photoHouse").val(list);
 	var checkCase=$this.hasClass('act-ago');
	var result15=baseInfoForm.uploadImg({targetSelector:$("#photoHouse"),noticeMsg:"房源照片"});
	var result14=baseInfoForm.testText({targetSelector:$("#gma_recommend"),noticeMsg:"推荐理由"});
	var result13=baseInfoForm.testText({targetSelector:$("#livingSituation"),noticeMsg:"居住情况"});
	var result12=baseInfoForm.testText({targetSelector:$("#houseType"),noticeMsg:"房屋类型"});
	var result11=baseInfoForm.testText({targetSelector:$("#decorate"),noticeMsg:"装修"});
	var result10=baseInfoForm.testText({targetSelector:$("#gma_housePrice"),noticeMsg:"报价"});
	var result9=baseInfoForm.testText({targetSelector:$("#gma_houseArea"),noticeMsg:"建筑面积"});
	var result8=baseInfoForm.testText({targetSelector:$("#gma_SumFloor"),noticeMsg:"总楼层"});
	var result7=baseInfoForm.testText({targetSelector:$("#gma_floor"),noticeMsg:"楼层"});
	var result6=baseInfoForm.testText({targetSelector:$("#orientation"),noticeMsg:"房屋朝向"});
	var result4=baseInfoForm.testText({targetSelector:$("#gma_office"),noticeMsg:"户型"});
	var result5=baseInfoForm.testText({targetSelector:$("#gma_toilet"),noticeMsg:"户型"});
	var result3=baseInfoForm.testText({targetSelector:$("#gma_room"),noticeMsg:"户型"});
	var result2=baseInfoForm.testText({targetSelector:$("#houseAddress"),noticeMsg:"房屋地址"});
 	var result1=baseInfoForm.testText({targetSelector:$("#cellName"),noticeMsg:"小区名称"});
 	var sendData=common.getSendDataByForm(baseInfoForm.form);
 	// console.log(sendData);
	if(!!checkCase&&!!result1&&!!result2&&!!result3&&!!result4&&!!result5&&!!result6&&!!result7&&!!result8&&!!result9&&!!result10&&!!result11&&!!result12&&!!result13&&!!result14&&!!result15){
    $this.removeClass("act-ago").addClass("acted-yet");
     baseInfoForm.formPost({
            sendData:sendData,
            url:url,
            resSuccess:function(data){
                actedStyle();
                $dialog.removeClass('gma_dialogHide').addClass('gma_dialog');
                $mask.removeClass('gma_dialogHide').addClass('gma_dialog');
                setTimeout(function(){
                	$dialog.removeClass('gma_dialog').addClass('gma_dialogHide');
                	$mask.removeClass('gma_dialog').addClass('gma_dialogHide');
                	window.location.href="submitHouse.html";
                },1000)
                baseInfoForm.form[0].reset();    
            },
            resFailed:function(data){
                 actAgoStyle (); 
                 //判断token失效
            	if(data['code']=="102"){
            		window.location.href="login.html";
            	};
            }
       }); 
    }else{
        console.log("不准发送ajax");
    };
 	e.preventDefault();
	return false;
 });
function actedStyle () {
    baseInfoForm.submit.removeClass("act-ago").addClass("acted-yet");
};
function actAgoStyle () {
    baseInfoForm.submit.removeClass("acted-yet").addClass("act-ago");
};
//上传图片
uploadImg({
	selectorBtn:$("#upload"),
	selectorUl:$('#gma_box'),
	selectorHidden:$("#photoHouse"),
	agentId:data.id,
	token:data.token,
	url:common.globalHost+common.uploadBasePort
});
function uploadImg(options){
	var selectorBtn = $(options.selectorBtn);
	var selectorUl =$(options.selectorUl);
	var selectorHidden =$(options.selectorHidden);
	var agentId=options.agentId;
	var url=options.url;
	  //    用于压缩图片的canvas
	var canvas = document.createElement("canvas");
	var ctx = canvas.getContext('2d');
	var maxsize = 100 * 1024;
  	var compressWidth=900;
  	selectorBtn.off("change").on("change",function() {
        var fileData = this.files[0];
        var imgSize = fileData.size/1024/1000;
        //console.log(size);
        if(imgSize>8){
            alert("图片过大");
        }else{
          // console.log(selectorUl.children().length)
        if(selectorUl.children().length>7){
          // console.log(selectorBtn.parent());
          selectorBtn.parent().hasClass('gma_uploadHide')?null:selectorBtn.parent().addClass('gma_uploadHide');
        }
        if (!this.files.length) return;
        var files = Array.prototype.slice.call(this.files);
        if (files.length > 9) {
          // alert("最多同时只可上传9张图片");
          return;
        }
      files.forEach(function(file, i) {
        if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
        var reader = new FileReader();
  //          获取图片大小
        var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
        //$(".img-list").append($(li));
        reader.readAsDataURL(file);
        reader.onload = function() {
          var result = this.result;
          var img = new Image();
          img.src = result;
          if (result.length <= maxsize) {
            img = null;
            upload(result,agentId,token,selectorUl,selectorHidden,url);
            return;
          }
  //      图片加载完毕之后进行压缩，然后上传
          if (img.complete) {
            callback();
          } else {
            img.onload = callback;
          }
          function callback() {
            var data = compress(img,compressWidth);
            upload(data,agentId,token,selectorUl,selectorHidden,url);
            img = null;
          }
        };
        
      })
      }
      
  });
  //    使用canvas对大图片进行压缩
  function compress(img,compressWidth) {
    var imgWidth=img.naturalWidth;
    var imgHeight=img.naturalHeight;
    var ctxImgHeight= (compressWidth)*(imgHeight/imgWidth);
    // console.log(ctxImgHeight);
    canvas.width=compressWidth;
    canvas.height=ctxImgHeight;
    ctx.clearRect(0, 0, compressWidth, ctxImgHeight);
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, compressWidth, ctxImgHeight);
    ctx.drawImage(img,0,0,compressWidth,ctxImgHeight);
    var ndata = canvas.toDataURL("image/jpeg",0.98);
    return ndata;
  }
  function upload(ndata,agentId,token,selectorUl,selectorHidden,url){
  	var currentTime=new Date().getTime();
    var oLi=$('<li data-time="'+currentTime+'"></li>');
    var oImg=$('<img src="'+ndata+'" alt=""/>');
    var oLoading=$('<p class="loading"></p>');
    var oMask=$('<p class="mask"></p>');
    var oSpan=$('<span class="gma_close"></span>');
    oLi.append(oImg);
    oLi.append(oSpan);
    oLi.append(oLoading);
    oLi.append(oMask);
    selectorUl.append(oLi);
    var sendData= {
        fileName:"H5_house_"+new Date().getTime(),
        folder:"house",
        id:agentId,
        uploadData:ndata,
        token:token
    };
  $.ajax
    ({
        data:sendData,
        type: "POST",
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        dataType:"json",
        url:url,
        success:function(data){
            if(typeof data==="string"){
                data=JSON.parse(data);
            }
            var code=data.code;
            if(data.code==0){
              var record = data.res.data;
              // console.log(data);
              arr.push({time:currentTime,record:record.filePath});
              var oNoticeSucceed=$('<p class="upload-notice" style="text-align:center">上传成功</p>')
              oLi.append(oNoticeSucceed);
              setTimeout(function(){
                oNoticeSucceed.remove();
              },1000); 
            }else{
              var oNoticeFailed=$('<p class="upload-notice" style="text-align:center">上传失败</p>')
              oLi.append(oNoticeFailed);
              setTimeout(function(){
                oNoticeFailed.remove();
              },1000); 
            }
            oLoading.hide();
            oMask.hide();
        },
        timeout:30000,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
         var oNoticeFailed=$('<p class="upload-notice" style="text-align:center">网络不畅,请稍候重试</p>')
              oLi.append(oNoticeFailed);
              setTimeout(function(){
                oNoticeFailed.remove();
              },1000); 
          oLoading.hide();
          oMask.hide();
          console.log('网络不畅');
        } 
    }); 

	}

}
